const express = require("express");
const pool = require("../pool.js");

const deviceRouter = express.Router();
module.exports = deviceRouter;

// 获取所有设备的名称和图片
deviceRouter.get("/findAll", (req, res,next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var sql = `select count(devid) as count from device`;
  pool.query(sql, (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    sql = `SELECT devname,devimg FROM device limit ?,?`;
    pool.query(sql, [offset, pagesize], (err, r) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, data: r, pagecount });
    });
  });
});

// 获取设备详情
deviceRouter.get("/detail", (req, res,next) => {
  var devname = req.query.devname;
  var sql = `SELECT * FROM device where devname=?`;
  pool.query(sql, [devname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 200, msg: "ok", data: r });
    } else {
      res.send({ code: 201, msg: "没有此设备" });
    }
  });
});

// 插入设备
deviceRouter.post("/insert", (req, res,next) => {
  var devname = req.body.devname;
  var devimg = req.body.devimg;
  var devdetail = req.body.devdetail;
  var sql1 = `select devid from device where devname=?`;
  pool.query(sql1, [devname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 201, msg: "设备已存在" });
    } else {
      var sql2 = `insert into device values(null,?,?,?)`;
      pool.query(sql2, [devname, devimg, devdetail], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "插入新设备成功" });
      });
    }
  });
});

// 删除设备
deviceRouter.delete("/delete", (req, res,next) => {
  var devname = req.query.devname;
  var sql = `delete from device where devname=?`;
  pool.query(sql, [devname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) res.send({ code: 201, msg: "无此设备" });
    else res.send({ code: 200, msg: "删除成功" });
  });
});
